/**
 * Copyright (C) 2017 PatSnap Pte Ltd, All Rights Reserved.
 */

package com.job.common.util;


import com.job.common.exception.UtilException;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Author: Tory
 * Date: 11/1/17
 * Time: 9:46 PM
 */
public class FileUtils {

    public static String uploadFile(byte[] file, String filePath) throws IOException {
        return uploadFile(file, filePath, UniqueString.uuidUniqueString());
    }

    private static String uploadFile(byte[] file, String filePath, String fileName) throws IOException {
        if (file.length == 0) {
            throw new UtilException("File is empty.");
        }

        if (StringUtils.isBlank(fileName)) {
            throw new UtilException("File name is blank.");
        }
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        String fullPath = filePath + "/" + fileName;
        FileOutputStream out = new FileOutputStream(fullPath);
        out.write(file);
        out.flush();
        out.close();
        return fullPath;
    }


    public void inputStreamToFile(InputStream ins, File file) throws IOException {
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
    }
}
